import {Pipe, PipeTransform} from '@angular/core';

@Pipe({
    name: 'money'
})
export class MoneyPipe implements PipeTransform {

    transform(value: any, type: string = '{{ \'￥\'  }}', i: number = -1, minFractionDigits: number = 2): any {
        switch (type) {
            case '{{ \'￥\'  }}':
                return this.moneyFormat(value);
            case '$':
                return this.moneyFormat(value, '$');
            case 'CNY':
                return (i == -1) && Number(value).toFixed(minFractionDigits) || ((i + 1) * (i + 1) && Number(value).toFixed(minFractionDigits).split('.')[i]);
        }
        return '';
    }

    /**
     * 货币格式转换
     * @param value 数值
     * @param symbol? 符号
     * @param thousand?
     * @param decimal?
     */
    private moneyFormat(value, places?, symbol?, thousand?, decimal?): any {
        places = !isNaN(places = Math.abs(places)) ? places : 2;
        // symbol = symbol !== undefined ? symbol : '￥';
        thousand = thousand || ',';
        decimal = decimal || '.';
        let number = value;
        let negative = number < 0 ? '-' : '';
        let i: any = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + '';
        let j = i.length;
        j = j > 3 ? j % 3 : 0;
        // symbol +
        return negative + (j ? i.substr(0, j) + thousand : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : '');
    }

}
